import { Toast } from 'vant'
import { login } from '@/api/user'
import { clearSession, getSession, setSession } from '@/utils/sessionTool'

const sessionKey = 'userInfo'

const sessionUserInfo = getSession(sessionKey) ? JSON.parse(getSession(sessionKey)) : {}

const state = {
  name: sessionUserInfo.name || '',
  mobile: sessionUserInfo.mobile || '',
  userid: sessionUserInfo.userid || '',
  token: getSession('token') ? getSession('token') : ''
}
const mutations = {
  SET_USERINFO: (state, { name, mobile, userid }) => {
    state.name = name || ''
    state.mobile = mobile || ''
    state.userid = userid || ''
    setSession(sessionKey, JSON.stringify({ name, mobile, userid }))
  },
  SET_TOKEN(state, token) {
    state.token = token
    setSession('token', state.token)
  },
  logout: state => {
    state.name = ''
    state.mobile = ''
    state.userid = ''
    state.token = ''
    clearSession()
  }
}

const actions = {
  async login({ commit }) {
    const loading = Toast.loading()
    try {
      const { token } = await login()
      commit('SET_TOKEN', token)
      return Promise.resolve(token)
    } catch (error) {
      return Promise.reject(error)
    } finally {
      loading.clear()
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
